package knowledge

import (
	"context"
	"encoding/xml"
	"net/http"
	"time"
)

// BlogSource represents a technical blog source
type BlogSource struct {
	config      *SourceConfig
	client      *http.Client
	lastUpdated time.Time
	cache       map[string]*Document
}

// NewBlogSource creates a new blog source
func NewBlogSource(config *SourceConfig) *BlogSource {
	return &BlogSource{
		config: config,
		client: &http.Client{
			Timeout: time.Second * 30,
		},
		cache: make(map[string]*Document),
	}
}

// Fetch implements Source interface
func (s *BlogSource) Fetch(ctx context.Context, query string) ([]*Document, error) {
	// Check cache first
	if doc, ok := s.cache[query]; ok {
		return []*Document{doc}, nil
	}

	// Fetch RSS/Atom feed
	req, err := http.NewRequestWithContext(ctx, "GET", s.config.URL, nil)
	if err != nil {
		return nil, err
	}

	resp, err := s.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var feed struct {
		Items []struct {
			Title   string `xml:"title"`
			Content string `xml:"content"`
			Link    string `xml:"link"`
			PubDate string `xml:"pubDate"`
		} `xml:"item"`
	}

	if err := xml.NewDecoder(resp.Body).Decode(&feed); err != nil {
		return nil, err
	}

	// Convert feed items to documents
	var docs []*Document
	for _, item := range feed.Items {
		doc := &Document{
			ID:      item.Link,
			Content: item.Content,
			Metadata: map[string]interface{}{
				"title":    item.Title,
				"url":      item.Link,
				"pub_date": item.PubDate,
				"type":     string(SourceTypeBlog),
			},
		}
		docs = append(docs, doc)
		s.cache[doc.ID] = doc
	}

	return docs, nil
}
